package com.ruoyi.web.controller.dongfang;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.question.domain.DfFile;
import com.ruoyi.question.domain.DfQuestionChild;
import com.ruoyi.question.service.IDfFileService;
import com.ruoyi.question.service.IDfQuestionChildService;
import com.ruoyi.system.domain.SysDept;
import com.ruoyi.system.domain.SysDictData;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysDictDataService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.question.domain.DfQuestion;
import com.ruoyi.question.service.IDfQuestionService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.ruoyi.framework.util.ShiroUtils.getSysUser;

/**
 * 问题 信息操作处理
 * 
 * @author ruoyi
 * @date 2019-09-09
 */
@Controller
@RequestMapping("/question/dfQuestion")
public class DfQuestionController extends BaseController
{
    private String prefix = "question/dfQuestion";
	
	@Autowired
	private IDfQuestionService dfQuestionService;
	@Autowired
	private ISysDeptService deptService;
	@Autowired
	private IDfQuestionChildService dfQuestionChildService;
	@Autowired
	private IDfFileService dfFileService;
    @Autowired
    private ISysDictDataService dictDataService;

	@RequiresPermissions("question:dfQuestion:view")
	@GetMapping()
	public String dfQuestion()
	{
	    return prefix + "/dfQuestion";
	}
	/**
	 * 查询问题列表
	 */
	@RequiresPermissions("question:dfQuestion:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(DfQuestion dfQuestion,ModelMap mmap)
	{
		startPage();
		SysUser currentUser = getSysUser();
		dfQuestion.setUserId(currentUser.getUserId());
        List<DfQuestion> list = dfQuestionService.selectDfQuestionList(dfQuestion);
        mmap.put("dfQuestionChild",list);
		return getDataTable(list);
	}
	
	
	/**
	 * 导出问题列表
	 */
	@RequiresPermissions("question:dfQuestion:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(DfQuestion dfQuestion)
    {
    	List<DfQuestion> list = dfQuestionService.selectDfQuestionList(dfQuestion);
        ExcelUtil<DfQuestion> util = new ExcelUtil<DfQuestion>(DfQuestion.class);
        return util.exportExcel(list, "dfQuestion");
    }
	
	/**
	 * 新增问题
	 */
	@GetMapping("/add")
	public String add(ModelMap mmap)
	{
		SysUser currentUser = getSysUser();
		Long deptId = currentUser.getDeptId();
		SysDept currentDept = deptService.selectDeptById(deptId);
		mmap.put("user", currentUser);
		mmap.put("dept", currentDept );
		return prefix + "/add";
	}


	/**
	 * 新增保存问题
	 */
	@RequiresPermissions("question:dfQuestion:add")
	@Log(title = "问题", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public AjaxResult addSave(DfQuestion dfQuestion)
	{
		DfQuestion newDfQuestion = new DfQuestion();
		newDfQuestion.setQuestionType(dfQuestion.getQuestionType());
		List<DfQuestion> list = dfQuestionService.selectDfQuestionList(newDfQuestion);
        dfQuestion.setCreatetime(new Date());
		//获取当年年份
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
		Date date = new Date();
		String year = sdf.format(date);
		//问题编号  如果是处理类型 存储格式2019010001
		if ("2".equals(dfQuestion.getQuestionType())){
			if (list.size() > 0){
				String questionNumber = list.get(0).getQuestionNumber();
				//判断当前年份是否和最新一条数据的年份相同
				if (questionNumber.substring(0,4).equals(year)){
					dfQuestion.setQuestionNumber(Integer.parseInt(questionNumber) + 1+"");
				} else {
					dfQuestion.setQuestionNumber(year+"010001");
				}

			} else {
				dfQuestion.setQuestionNumber(year+"010001");
			}
		}
		//如果是处理类型 存储格式2019020001
		if ("3".equals(dfQuestion.getQuestionType())){
			if (list.size() > 0){
				String questionNumber = list.get(0).getQuestionNumber();
				//判断当前年份是否和最新一条数据的年份相同
				if (questionNumber.substring(0,4).equals(year)){
					dfQuestion.setQuestionNumber(Integer.parseInt(questionNumber) + 1+"");
				} else {
					dfQuestion.setQuestionNumber(year+"020001");
				}
			} else {
				dfQuestion.setQuestionNumber(year+"020001");
			}
		}
		dfQuestionService.insertDfQuestion(dfQuestion);
		return AjaxResult.success(dfQuestion.getId());
	}

	/**
	 * 修改问题
	 */
	@GetMapping("/edit/{id}")
	public String edit(@PathVariable("id") Long id, ModelMap mmap)
	{
		DfQuestion dfQuestion = dfQuestionService.selectDfQuestionById(id);
		mmap.put("dfQuestion", dfQuestion);
		getQuestionInfo(id, mmap,dfQuestion);
	    return prefix + "/edit";
	}
	
	/**
	 * 修改保存问题
	 */
	@RequiresPermissions("question:dfQuestion:edit")
	@Log(title = "问题", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public AjaxResult editSave(DfQuestion dfQuestion)
	{		
		dfQuestion.setUpdatetime(null);
	    return toAjax(dfQuestionService.updateDfQuestion(dfQuestion));
	}
	
	/**
	 * 删除问题
	 */
	@RequiresPermissions("question:dfQuestion:remove")
	@Log(title = "问题", businessType = BusinessType.DELETE)
	@PostMapping( "/remove")
	@ResponseBody
	public AjaxResult remove(String ids)
	{		
		return toAjax(dfQuestionService.deleteDfQuestionByIds(ids));
	}

	/**
	 * 查看问题
	 * @param id
	 * @param mmap
	 * @return
	 */
	@GetMapping("/view/{id}")
	public String view(@PathVariable("id") Long id, ModelMap mmap)
	{
		DfQuestion dfQuestion = dfQuestionService.selectDfQuestionById(id);
		mmap.put("dfQuestion", dfQuestion);
		SysUser currentUser = getSysUser();
		mmap.put("level",getUserLevel(currentUser.getDeptId()));
		if ("9".equals(dfQuestion.getQuestionState())||"10".equals(dfQuestion.getQuestionState())){
			getQuestionInfo(id, mmap,dfQuestion);
			return prefix + "/view";
		}
		getQuestionInfo(id, mmap,dfQuestion);
		return prefix + "/viewQuestionAgain";
	}

	/**
	 * 获取问题答案(共用代码)
	 * @param id
	 * @param mmap
	 */
	private void getQuestionInfo(@PathVariable("id") Long id, ModelMap mmap,DfQuestion dfQuestion) {
		DfFile dfFile1 = new DfFile();
		dfFile1.setQuestionId(id);
		dfFile1.setFileSource("1");
		List<DfFile> files1 = dfFileService.selectDfFileList(dfFile1);
		for (int i = 0; i < files1.size(); i++) {
			DfFile file = files1.get(i);
			file.setFileId("http://211.149.205.33:18080/file/down/"+file.getFileId());
		}
		dfQuestion.setFiles(files1);
		DfQuestionChild dfQuestionChild = new DfQuestionChild();
		dfQuestionChild.setQuestionId(id);
		List<DfQuestionChild> list = dfQuestionChildService.selectDfQuestionChildList(dfQuestionChild);
		for (int i = 0; i <list.size() ; i++) {
			DfQuestionChild dfQuestionChild1 = list.get(i);
			DfFile dfFile = new DfFile();
			dfFile.setQuestionId(dfQuestionChild1.getId());
			dfFile.setFileSource("2");
			List<DfFile> files = dfFileService.selectDfFileList(dfFile);
			for (int j = 0; j < files.size(); j++) {
				DfFile file1 = files.get(j);
				file1.setFileId("http://211.149.205.33:18080/file/down/"+file1.getFileId());
			}
			dfQuestionChild1.setFiles(files);
		}
		mmap.put("dfQuestionChild",list);
	}

	/**
	 * 用户点击解决问题
	 */
	@PostMapping("/passApprove")
	@ResponseBody
	public AjaxResult passApprove (DfQuestion dfQuestion){
		//更新问题状态为已解决
		dfQuestion.setQuestionState("9");
		dfQuestion.setUpdatetime(new Date());
		return toAjax(dfQuestionService.updateDfQuestion(dfQuestion));
	}


	/**
	 * pinglun问题
	 */
	@GetMapping("/comment/{id}")
	public String comment(@PathVariable("id") Long id, ModelMap mmap)
	{
		DfQuestion dfQuestion = dfQuestionService.selectDfQuestionById(id);
		mmap.put("dfQuestion", dfQuestion);
		return prefix + "/comment";
	}
	/**
	 * 保存评论
	 */
	@PostMapping("/saveComment")
	@ResponseBody
	public AjaxResult saveComment (DfQuestion dfQuestion){

		return toAjax(dfQuestionService.updateDfQuestion(dfQuestion));
	}
	/**
	 * 查看问题进度
	 */
	@GetMapping("/checkSchedule/{id}")
	public String checkSchedule(@PathVariable("id") Long id, ModelMap mmap)
	{
		DfQuestion dfQuestion = dfQuestionService.selectDfQuestionById(id);
		mmap.put("dfQuestion", dfQuestion);

		getQuestionInfo(id, mmap,dfQuestion);
		return prefix + "/questionSchedule";
	}

	@Log(title = "问题管理", businessType = BusinessType.IMPORT)
	@PostMapping("/importData")
	@ResponseBody
	public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
	{
		SysUser currentUser = getSysUser();
		ExcelUtil<DfQuestion> util = new ExcelUtil<DfQuestion>(DfQuestion.class);
		List<DfQuestion> questionList = util.importExcel(file.getInputStream());
		for (int i = 0; i < questionList.size(); i++) {
			DfQuestion dfQuestion = questionList.get(i);
			dfQuestion.setUserId(currentUser.getUserId());
			dfQuestion.setUserName(currentUser.getUserName());
			dfQuestion.setUserPhone(currentUser.getPhonenumber());
			dfQuestion.setUserDept(currentUser.getDept().getDeptName());
			dfQuestion.setUserDeptId(currentUser.getDeptId());
            if (dfQuestion.getQuestionType().equals("处理")){
                dfQuestion.setQuestionType("2");
            }else{
                dfQuestion.setQuestionType("3");
            }
            dfQuestion.setQuestionVersion(getQuestionVersion(dfQuestion.getQuestionVersion()));
            DfQuestion newDfQuestion = new DfQuestion();
            newDfQuestion.setQuestionType(dfQuestion.getQuestionType());
            List<DfQuestion> list = dfQuestionService.selectDfQuestionList(newDfQuestion);
            dfQuestion.setCreatetime(new Date());
            //获取当年年份
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
            Date date = new Date();
            String year = sdf.format(date);
            //问题编号  如果是处理类型 存储格式2019010001
            if ("2".equals(dfQuestion.getQuestionType())){
                if (list.size() > 0){
                    String questionNumber = list.get(0).getQuestionNumber();
                    //判断当前年份是否和最新一条数据的年份相同
                    if (questionNumber.substring(0,4).equals(year)){
                        dfQuestion.setQuestionNumber(Integer.parseInt(questionNumber) + 1+"");
                    } else {
                        dfQuestion.setQuestionNumber(year+"010001");
                    }

                } else {
                    dfQuestion.setQuestionNumber(year+"010001");
                }
            }
            //如果是处理类型 存储格式2019020001
            if ("3".equals(dfQuestion.getQuestionType())){
                if (list.size() > 0){
                    String questionNumber = list.get(0).getQuestionNumber();
                    //判断当前年份是否和最新一条数据的年份相同
                    if (questionNumber.substring(0,4).equals(year)){
                        dfQuestion.setQuestionNumber(Integer.parseInt(questionNumber) + 1+"");
                    } else {
                        dfQuestion.setQuestionNumber(year+"020001");
                    }
                } else {
                    dfQuestion.setQuestionNumber(year+"020001");
                }
            }
			dfQuestion.setQuestionExpert("0");
            dfQuestionService.insertDfQuestion(dfQuestion);
		}
		return AjaxResult.success();
	}

	private String getQuestionVersion(String version){
	    SysDictData dictData = new SysDictData();
	    dictData.setDictType("df_question_version");
        List<SysDictData> list = dictDataService.selectDictDataList(dictData);
        for (int i = 0; i < list.size(); i++) {
            SysDictData sysDictData = list.get(i);
            if (sysDictData.getDictLabel().equals(version)){
                return sysDictData.getDictValue();
            }
        }
        return "3";
    }

}
